<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="header">
          <img src="/logo.png" alt="StoryPlush" class="logo" />
          <h2>欢迎回来</h2>
          <p class="subtitle">登录您的 StoryPlush 账号</p>
        </div>
      </template>
      
      <el-form 
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            :prefix-icon="User"
            :disabled="loading"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            :prefix-icon="Lock"
            :disabled="loading"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <div class="form-footer">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <el-link type="primary" @click="router.push('/forgot-password')">
            忘记密码？
          </el-link>
        </div>
        
        <el-button
          type="primary"
          :loading="loading"
          @click="handleLogin"
          class="login-button"
        >
          登录
        </el-button>

        <div class="register-link">
          还没有账号？
          <el-link type="primary" @click="router.push('/register')">
            立即注册
          </el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref(null)

const loginForm = ref({
  username: '',
  password: ''
})

const rememberMe = ref(false)
const loading = ref(false)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在 3 到 20 个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        console.log('Attempting login:', loginForm.value.username)
        
        const { data } = await axios.post('/api/auth/login', loginForm.value)
        
        if (!data.success) {
          throw new Error(data.message)
        }

        // 存储用户信息和token
        userStore.setToken(data.data.token)
        userStore.setUser(data.data.user)
        
        // 如果选择记住我，保存用户名
        if (rememberMe.value) {
          localStorage.setItem('remembered_username', loginForm.value.username)
        } else {
          localStorage.removeItem('remembered_username')
        }
        
        ElMessage.success('登录成功')
        router.push('/')
      } catch (error) {
        console.error('Login error:', error)
        ElMessage.error(error.response?.data?.message || '登录失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 页面加载时检查是否有记住的用户名
onMounted(() => {
  const rememberedUsername = localStorage.getItem('remembered_username')
  if (rememberedUsername) {
    loginForm.value.username = rememberedUsername
    rememberMe.value = true
  }
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.3)), url('/images/login-bg.jpg');
  background-size: cover;
  background-position: center;
}

.login-card {
  width: 100%;
  max-width: 400px;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(8px);
  background-color: rgba(255, 255, 255, 0.7);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.login-card:hover {
  box-shadow: 0 12px 36px rgba(0, 0, 0, 0.25);
  background-color: rgba(255, 255, 255, 0.75);
}

.header {
  text-align: center;
  padding: 10px 0;
}

.logo {
  width: 120px;
  margin-bottom: 16px;
  filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.1));
}

.subtitle {
  color: #444;
  font-size: 14px;
  margin-top: 8px;
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-input__wrapper:hover) {
  border-color: rgba(78, 111, 255, 0.3);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px rgba(78, 111, 255, 0.3);
  border-color: rgba(78, 111, 255, 0.5);
}

.form-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.register-link {
  text-align: center;
  margin-top: 16px;
  color: #444;
  font-weight: 500;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__inner) {
  padding: 12px;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #4e6fff 0%, #3e5cd8 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(78, 111, 255, 0.3);
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a7aff 0%, #4968e6 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(78, 111, 255, 0.4);
  transition: all 0.3s ease;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #4e6fff;
  border-color: #4e6fff;
}

:deep(.el-link.el-link--primary) {
  color: #4e6fff;
}

:deep(.el-link.el-link--primary:hover) {
  color: #5a7aff;
}
</style> 